<?php

namespace app\admin\controller\wanlshop;

use app\admin\model\User;
use app\api\service\UserService;
use app\common\controller\Backend;
use app\common\model\UserExtra;
use think\Db;
use think\Exception;

use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 提现管理
 *
 * @icon fa fa-circle-o
 */
class Withdraw extends Backend
{
    
    /**
     * Withdraw模型对象
     * @var \app\admin\model\wanlshop\Withdraw
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Withdraw;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
	
	/**
	 * 查看
	 */
	public function index()
	{
	    //当前是否为关联查询
	    $this->relationSearch = true;
	    //设置过滤方法
	    $this->request->filter(['strip_tags', 'trim']);
	    if ($this->request->isAjax())
	    {
	        //如果发送的来源是Selectpage，则转发到Selectpage
	        if ($this->request->request('keyField'))
	        {
	            return $this->selectpage();
	        }
	        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
	        $total = $this->model
//	                ->with(['bank',"user"])
	                ->where($where)
	                ->order($sort, $order)
	                ->count();
	
	        $list = $this->model
//	                ->with(['bank',"user"])
	                ->where($where)
	                ->order($sort, $order)
	                ->limit($offset, $limit)
	                ->select();
	
	        foreach ($list as &$row) {
                $row["bank"] = db("wanlshop_pay_account")
                    ->where("user_id",$row["user_id"])
                    ->where("cardCode",$row["account"])
                    ->field("username")
                    ->find();
                $row["user"] = db("user")
                    ->where("id",$row["user_id"])
                    ->field("mobile")
                    ->find();

//	            $row->getRelation('bank')->visible(['username']);
//	            $row->getRelation('user')->visible(['mobile']);
	        }
	        $list = collection($list)->toArray();
	        $result = array("total" => $total, "rows" => $list);
	
	        return json($result);
	    }
	    return $this->view->fetch();
	}
	
	
    /**
     * 详情
     */
    public function detail($ids = null)
    {
    	$row = $this->model->get($ids);
    	if (!$row) {
    	    $this->error(__('No Results were found'));
    	}
		$row['bank'] = model('app\admin\model\wanlshop\PayAccount')
			->where(['cardCode' => $row['account'], 'user_id' => $row['user_id']])
			->find();
        $row['user'] = model('app\admin\model\User')
            ->where(['id' => $row['user_id']])
            ->find();
    	$this->view->assign("row", $row);
    	return $this->view->fetch();
    }
    
    /**
     * 同意
     */
    public function agree($ids = null)
    {
    	$row = $this->model->get($ids);
    	if (!$row) {
    	    $this->error(__('No Results were found'));
    	}
    	$adminIds = $this->getDataLimitAdminIds();
    	if (is_array($adminIds)) {
    	    if (!in_array($row[$this->dataLimitField], $adminIds)) {
    	        $this->error(__('You have no permission'));
    	    }
    	}
    	if ($row['status'] == 'successed') {
    	    $this->error(__('已审核过本店铺，请不要重复审核！'));
    	}
        $user = db("user")->where("id",$row["user_id"])->find();
    	if ($this->request->isPost()) {
    		$result = false;
            $user_list = $this->get_same_level_user($row["user_id"]);
            $success_user = [];
            foreach ($user_list as $v){
                $prize_score = db("user_money_log")->where('type',"in",["prize_draw","share","upgrade"])->where("user_id",$v)->sum("money");
                if ($prize_score < 5197){
                    $success_user[] = $v;
                }
            }
            $money_log = [];
            if (count($success_user) > 0){
                $once_money = bcdiv(bcmul($row["handingfee"],0.1,2),count($success_user),2);
            }else{
                $once_money = 0;
            }

            foreach ($success_user as $v1){
                $v_user = db("user")->where("id",$v1)->find();
                $money_log[] = [
                    "user_id" => $v1,
                    "money" => $once_money,
                    "before" => $v_user["money"],
                    "after" => bcadd($v_user["money"],$once_money,2),
                    "memo" => $this->desMobile($user["mobile"]).":协助补贴积分",
                    "type" => "share",
                    "createtime" => time(),
                ];
            }
    		Db::startTrans();
    		try {
    		    //是否采用模型验证
    		    if ($this->modelValidate) {
    		        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
    		        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
    		        $row->validateFailException(true)->validate($validate);
    		    }
    			// 审核通过
    		    $result = $row->allowField(true)->save([
					'status' => 'successed',
					'transfertime' => time()
				]);
                if(count($success_user) > 0){
                    db("user")->where("id","in",$success_user)->inc("money",$once_money)->inc("score",$once_money)->update(["updatetime"=>time()]);
                    db("user_money_log")->insertAll($money_log);
                }
    		    Db::commit();
    		} catch (ValidateException $e) {
    		    Db::rollback();
    		    $this->error($e->getMessage());
    		} catch (PDOException $e) {
    		    Db::rollback();
    		    $this->error($e->getMessage());
    		} catch (Exception $e) {
    		    Db::rollback();
    		    $this->error($e->getMessage());
    		}
    		if ($result !== false) {
    		    $this->success();
    		} else {
    		    $this->error(__('No rows were updated'));
    		}
    	}
    	$this->view->assign("row", $row);
    	return $this->view->fetch();
    }

    private function desMobile($mobile)
    {
        if (strlen($mobile) != 11) {
            return $mobile; // 如果手机号长度不是11位，直接返回原手机号
        }
        return mb_substr($mobile, 0, 3) . '****' . mb_substr($mobile, -4);
    }

    //获取符合条件的同级
    public function get_same_level_user($userid){
        $pid = db("user")->where("id",$userid)->value("pid");
        if($pid != null){
            $pid = db("user")->where("id",$pid)->value("pid");
            $user_arr_check = db("user")->where("pid",$pid)->column("id");
            $user_arr = db("user")->where("pid","in",$user_arr_check)->where("star",13)->column("id");
        }else{
            $user_arr = db("user")->where("pid",$pid)->where("star",13)->column("id");
        }
        return $user_arr;
    }
    
    /**
     * 拒绝
     */
    public function refuse($ids = null){
        // $this->error("功能维护中");
    	$row = $this->model->get($ids);
    	if (!$row) {
    	    $this->error(__('No Results were found'));
    	}
    	$adminIds = $this->getDataLimitAdminIds();
    	if (is_array($adminIds)) {
    	    if (!in_array($row[$this->dataLimitField], $adminIds)) {
    	        $this->error(__('You have no permission'));
    	    }
    	}
    	if ($this->request->isPost()) {
    	    $params = $this->request->post("row/a");
    	    if ($params) {
    	        $params = $this->preExcludeFields($params);
    	        $result = false;
    	        Db::startTrans();
    	        try {
    	            //是否采用模型验证
    	            if ($this->modelValidate) {
    	                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
    	                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
    	                $row->validateFailException(true)->validate($validate);
    	            }
    				$params['status'] = 'rejected';
    	            $result = $row->allowField(true)->save($params);
                    $user = User::get($row['user_id']);
                    $money1 = $user['money'];
                    $add_money = $row['money'];

                    $extra = UserExtra::get(['user_id' => $row['user_id']]);

					// 更新用户金额
				// 	controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+bcadd($row['money'], $row['handingfee'], 2), $row['user_id'], '寄售失败,积分返回', 'withdraw', $row['id']);
                    
                    $user->score = bcadd($user['score'], $row['money'], 2);
                    $user->money = $mm = bcadd($user['money'], $row['money'], 2);
                    $user->save();
                    
                    $extra->score = bcadd($extra['score'], $row['money'], 2);
                    $extra->save();
                    
                    UserService::getInstance()->cr_money_log($money1, $mm,$add_money,$user['id'], '寄售失败,积分返回', 'withdraw', $row['id']);
    	            Db::commit();
    	        } catch (ValidateException $e) {
    	            Db::rollback();
    	            $this->error($e->getMessage());
    	        } catch (PDOException $e) {
    	            Db::rollback();
    	            $this->error($e->getMessage());
    	        } catch (Exception $e) {
    	            Db::rollback();
    	            $this->error($e->getMessage());
    	        }
    	        if ($result !== false) {
    	            $this->success();
    	        } else {
    	            $this->error(__('No rows were updated'));
    	        }
    	    }
    	    $this->error(__('Parameter %s can not be empty', ''));
    	}
    	$this->view->assign("row", $row);
    	return $this->view->fetch();
    }
    

}
